<template>
<div id="appointment" class="appointment">
    <div class="appointment_top">
        <calendar ref="calendar1"
            :events="calendar1.events" 
            :disabled="calendar1.disabled"
            :lunar="calendar1.lunar" 
            :value="calendar1.value" 
            :begin="calendar1.begin" 
            :end="calendar1.end" 
            @selectDate="setSelectDate"
            @selectMonth="changeSelectMonth"
            @selectYear="calendar1.selectYear"></calendar>
    </div>

    <div class="appointment_bottom">
        <div v-if="loginStatus == 0">
            <div style="text-align:center;font-size:15px;">
                您需要登录后才能预约，点此<span style="color:#F0F026;" @click="login">登录</span>
            </div>
        </div>
        <div v-else>
            <div v-if="dateActived == 0">
                <div style="text-align:center;font-size:15px;color:#DC143C;">
                    还没有安排体检预约周期，不能进行预约。请联系管理员
                </div>
            </div>
            <div v-else>
                <div v-if="appointDisabled == 1">
                    <div style="text-align:center;font-size:15px;color:#DC143C;">
                        您的数据还未导入，不能进行预约。请联系管理员
                    </div>
                </div>
                <div v-else-if="healthUserInfo.state == 5">
                    <div style="text-align:center;font-size:15px;color:#DC143C;">
                        您的体检报告已经到达中粮集团医疗管理与服务部（福临门大厦东门外医务室），请您及时领取。
                    </div>
                </div>
                <div v-else-if="appointDisabled == 2">
                    <div v-if="healthUserInfo.state == 1 || healthUserInfo.state == 3">
                        <div style="text-align:center;font-size:15px;color:#DC143C;">
                            您选择的机构的当天预约名额已满，请选择其它体检机构或其它日期进行预约！
                        </div>
                    </div>
                </div>
                <div v-else>
                    <div v-if="orgAppointFlg == 0">
                        <div style="text-align:center;font-size:15px;color:#DC143C;">
                            当前月份还没有体检机构安排预约计划，不能进行预约
                        </div>
                    </div>
                    <div v-else-if="orgAppointFlg == 2">
                        <div style="text-align:center;font-size:15px;color:#DC143C;">
                            当前月份您的业务单元还没有安排体检机构，如果有需要请联系客服
                        </div>
                    </div>
                    <div v-else-if="orgAppointFlg == 3">
                        <div style="text-align:center;font-size:15px;color:#DC143C;">
                            当前月份您的业务单元安排的体检机构都没有升级套餐，如果有需要请联系客服
                        </div>
                    </div>
                    <div v-else>
                        <!-- 体检机构已安排预约计划  -->
                    </div>
                </div>
            </div>
        </div>
        <div style="margin-top:0.2rem">
            <yd-cell-group>
                <yd-cell-item>
                    <span slot="left">预约者姓名：</span>
                    <span slot="left">{{healthUserInfo.userName}}</span>
                </yd-cell-item>
                <!-- 手机端不要 -->
                <!-- <yd-cell-item>
                    <span slot="left">是否升级套餐：</span>
                    <select slot="left" v-model="selectedPkgUpgrade" @change="changePkgUpgrade()"  style="width:5.5rem;height:0.8rem;border:none;font-size:14px;font-family:Microsoft YaHei;">
                        <option value="">请选择</option>
                        <option value="1">是</option>
                        <option value="0">否</option>
                    </select>
                </yd-cell-item> -->
                <yd-cell-item>
                    <span slot="left">预约机构：</span>
                    <select slot="left" v-model="selectedOrg" @change="changeSelectedOrg()" style="width:5.5rem;height:0.8rem;border:none;font-size:14px;font-family:Microsoft YaHei;">
                        <option v-for="option in orgOptions" :key="option.value" v-bind:value="option.value">
                            {{option.text}}
                        </option>
                    </select>
                </yd-cell-item>
                <yd-cell-item>
                    <span slot="left">机构地址：</span>
                    <span slot="left" v-if="selectedOrg == 0" style="color:#ccc;font-size:12px;">体检机构选择后，就能看到机构地址</span>
                    <span slot="left" v-if="appointmentOrgInfo != null && appointmentOrgInfo.address != null && appointmentOrgInfo.address != '' && appointmentOrgInfo.address.length > 18">{{appointmentOrgInfo.address.substr(0, 18)}}</span>
                    <span slot="left" v-else>{{appointmentOrgInfo.address}}</span>
                </yd-cell-item>
                <yd-cell-item v-if="appointmentOrgInfo != null && appointmentOrgInfo.address != null && appointmentOrgInfo.address != '' && appointmentOrgInfo.address.length > 18">
                    <span slot="left">&nbsp;&nbsp;&nbsp;&nbsp;</span>
                    <span slot="left" style="margin-left:1.1rem">{{appointmentOrgInfo.address.substr(18)}}</span>
                </yd-cell-item>
                <!-- <yd-cell-item>
                    <span slot="left">剩余名额：</span>
                    <span slot="left" v-if="appointmentOrgInfo.remaindNum == 0" style="color:#DC143C;font-weight:bold">{{appointmentOrgInfo.remaindNum}}</span>
                    <span slot="left" v-else>{{appointmentOrgInfo.remaindNum}}</span>
                </yd-cell-item> -->
                <yd-cell-item>
                    <span slot="left">体检套餐：</span>
                    <select slot="left" v-model="selectedPkg"  style="width:5.5rem;height:0.8rem;border:none;font-size:14px;font-family:Microsoft YaHei;">
                        <option v-for="option in pkgOptions" :key="option.value" v-bind:value="option.value">
                            {{option.text}}
                        </option>
                    </select>
                </yd-cell-item>
            </yd-cell-group>
        </div>
        <div style="text-align:center;margin-left:0.5rem;margin-top:-0.5rem;">
            <yd-flexbox>
                <yd-flexbox-item style="text-align:left">
                    <div v-if="periodChecked == 0">
                        <!-- 预约可用 -->
                        <div v-if="loginStatus == 1 && dateActived == 1 && appointDisabled == 0 && orgAppointFlg == 1 && (healthUserInfo.state == 1 || healthUserInfo.state == 3)" 
                                class="appointment_btn" @click="checkup">
                            确定预约
                        </div>
                        <!-- 预约不可用 -->
                        <div v-else  class="appointment_btn" style="color:#D3D3D3">
                            确定预约
                        </div>
                    </div>
                    <div v-if="periodChecked == 1">
                        <!-- 重新预约可用 -->
                        <div v-if="loginStatus == 1 && dateActived == 1 && appointDisabled == 0 && orgAppointFlg == 1 && healthUserInfo.state == 2" 
                                class="appointment_btn" @click="reCheckup">
                            重新预约
                        </div>
                        <!-- 重新预约不可用 -->
                        <div v-else  class="appointment_btn" style="color:#D3D3D3">
                            重新预约
                        </div>
                    </div>
                </yd-flexbox-item>
                <yd-flexbox-item style="text-align:right">
                    <!-- 取消预约 -->
                    <div v-if="periodChecked == 1">
                        <!-- 重新预约可用 -->
                        <div v-if="loginStatus == 1 && dateActived == 1 && (appointDisabled == 0 || appointDisabled == 2) &&  orgAppointFlg == 1 && healthUserInfo.state == 2" 
                                class="appointment_btn"  @click="cancelCheckup">
                            取消预约
                        </div>
                        <!-- 重新预约不可用 -->
                        <div v-else  class="appointment_btn" style="color:#D3D3D3">
                            取消预约
                        </div>
                    </div>
                </yd-flexbox-item>
            </yd-flexbox>
        </div>
    </div>
    <div class="popContainer" v-show="popShow">
        <!-- POP 页面的遮罩层 -->
    </div>
    <div v-show="popShow" class="popBox">
        <!-- <yd-layout> -->
            <div style="margin-left:90%;margin-top:1%">
                <yd-icon style="color:gray" name="error" @click.native="popShow=false"></yd-icon>
            </div>
            <div class='popMsg'>
                <div class='popTitle'>请确认以下信息是否正确</div>
                <ul >
                    <li>受检人姓名：{{healthUserInfo.userName}}</li>
                    <li>身份证号：{{healthUserInfo.cardId}}</li>
                    <li>手机号码：{{healthUserInfo.mobPhone}}</li>
                    <li>性别：{{healthUserInfo.userSex | oUserSex}}</li>
                    <li>婚姻状况：{{healthUserInfo.isMarried | oIsMarried}}</li>
                    <li>所属部门：{{healthUserInfo.deptName | oDeptName}}</li>
                    <li>体检套餐：{{healthUserInfo.pkgName}}</li>
                    <li>是否升级套餐：{{selectedPkgUpgrade | oPkgUpgrade}}</li>
                    <li>体检日期：{{selectedDate}}</li>
                    <li>体检机构名称：{{appointmentOrgInfo.orgName}}</li>
                    <li>体检机构地址：{{appointmentOrgInfo.address}}</li>
                </ul>
                <!-- <yd-icon name="error"></yd-icon> -->
                <!-- <yd-button type="primary"><yd-icon name="checkoff"></yd-icon></yd-button> -->
                <div style="text-align: center">
                    <yd-button type="warning" @click.native="popShow=false">取消</yd-button>&nbsp;&nbsp;&nbsp;&nbsp;
                    <yd-button type="primary" @click.native="appointment('1', selectedDate)">确定</yd-button>
                </div>
            </div>
        <!-- </yd-layout> -->
    </div>
</div>
</template>

<script>
import moment from "moment";
import calendar from "@/components/calendar.vue";
import axios from "axios";

export default {
    name: "appointment",
    components: {
        calendar
    },
    data() {
        return {
            userid: "",
            initFlg: 1, // 1:页面初期化  2:初期化结束以后
            loginStatus: 1, // 0:未登录  1:已登录
            dateActived: 1, // 0:还没有安排预约周期  1:已预约周期
            appointDisabled: 0, // 0:该用户可以预约  1:该用户的数据还未导入  2:剩余名额不足不可以预约
            periodChecked: 0, // 0:预约周期内未预约  1:预约周期内已预约
            orgAppointFlg: 1, // 0:体检机构未安排预约计划  1:体检机构已安排预约计划  2：当前用户的业务单元的体检机构无 3：当前用户的业务单元安排的有升级套餐的体检机构无
            cycleStartDate: "", // 当前预约周期的开始日期
            cycleEndDate: "", // 当前预约周期的结束日期
            serverToday: "", // 服务器的当天日期 YYYY-MM-DD
            selectedDate: "",
            dateFormat: "-",
            appointmentMonthList: [],
            appointmentDateList: [],
            appointmentOrgInfo: {},
            healthUserInfo: {},
            healthUserDept: {},
            healthUserAppointmentInfo: [],  // 用户的已预约信息
            checkedDate: "",
            selectedPkgUpgrade: "",
            selectedOrg: "",
            orgOptions: [],
            selectedPkg: "",
            pkgOptions: [],
            popShow: false,
            calendar1: {
                value: [], //默认日期
                lunar: false, //显示农历
                // weeks:['日', '一', '二', '三', '四', '五', '六'],
                // months:['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                // events:{
                //     '2018-4-1':'已签',
                //     '2018-4-2':'已签',
                //     '2018-4-3':'已签',
                //     '2018-4-5':'已签',
                // },
                selectDate(value) {
                    // calendar.vue页面的 this.$emit("select", XXXX) 方法设定的值
                    console.log(value.toString());
                },
                selectMonth(month, year) {
                    console.log(year, month);
                },
                selectYear(year) {
                    console.log(year);
                },
                timestamp: Date.now()
            }
        };
    },
    created: function() {
        // 通过链接进入平台，但没有关注过公众号时,重新设定模式
        // 取得浏览器的信息（无论有没有设定过都需要重新设定）
        let userAgent = navigator.userAgent.toLowerCase();
        // 企业微信浏览器多了wxwork
        if (userAgent.indexOf("wxwork") > -1) {
            this.$store.commit("inMode", "qiye");
        } else {
            this.$store.commit("inMode", "weixin");
        }

        // android终端、ios终端的判断
        var u = navigator.userAgent;
        var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        if (isiOS) {
            this.dateFormat = "/";
        }

        this.userid = this.$store.state.userid;

        this.initFlg = 1;
        this.init();

        // 预约时需要跳转到登录时页面时，登录的跳转判断条件
        // 从员工关爱平台的广告栏进入该页面时this.$store.state.routerTo ="/"
        // 从微信公众的TAB菜单进入该页面时this.$store.state.routerTo = "/appointment"
        if (this.$store.state.routerTo != "/appointment") {
            this.$store.commit("routerTo", "/appointment");
        }
    },
    filters: {
        oUserSex(sex) {
            // 性别 1:男 2:女
            if (sex == 1) {
                return "男";
            } else if (sex == 2) {
                return "女";
            } else {
                return "未知";
            }
        },
        oDeptName(deptName) {
            if (deptName == null || deptName == "") {
                return "未填写";
            } else {
                return deptName;
            }
        },
        oPkgUpgrade(pkgUpgrade) {
            if (pkgUpgrade == '0') {
                return "否";
            } else if (pkgUpgrade == '1') {
                return "是";
            } else {
                return "未选择";
            }
        },
        oIsMarried(isMarried) {
            // 婚姻状况 0:未婚 1:已婚
            if (isMarried == 0) {
                return "未婚";
            } else if (isMarried == 1) {
                return "已婚";
            } else {
                return "未知";
            }
        }
    },
    methods: {
        init() {
            /*****************初期化*****************/
            // 用户ID有的场合，隐藏提示信息
            if (this.userid) {
                this.loginStatus = 1;
            } else {
                // 显示隐藏提示信息
                this.loginStatus = 0; // 未登录
                this.userid = "";
            }
        },
        changeSelectMonth(yearMonth, day) {
            /***********月份变化时的处理*************/
            // yearMonth == year + this.dateFormat + month
            this.selectedDate = yearMonth + this.dateFormat + day;
            
            let arrYearMonth = yearMonth.split(this.dateFormat);
            let selectYearMonth = arrYearMonth[0] + arrYearMonth[1];

            this.$dialog.loading.open("请稍后");

            // 页面第一次加载时
            if (this.initFlg == 1) {
                console.log("changeSelectMonth---11111----this.loginStatus==="+this.loginStatus)
                // 如果用户已经登录
                if (this.loginStatus == 1) {
                    axios.all([
                        this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/activeCycleList"),
                        this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/monthAppointList?yearMonth=" + selectYearMonth),
                        this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/userAppointList")
                    ])
                    .then(axios.spread((cycleResponse, everyMonthAppointResponse, userAppointmentResponse) => {
                        // 上面两个请求都完成后，才执行这个回调方法
                        this.$dialog.loading.close();

                        // 预约周期信息的取得取得
                        if (cycleResponse.status == 200) {
                            let healthCycleList = cycleResponse.data.object;
                            // 预约周期的设定处理
                            this.setActiveCycleList(healthCycleList);

                            // 预约周期信息取得时
                            this.initFlg == 2;

                            // 每个月所有机构的预约信息
                            // 当前用户的预约信息
                            if (everyMonthAppointResponse.status == 200 &&
                                    userAppointmentResponse.status == 200) {

                                let userAppointmentList = userAppointmentResponse.data.object;
                                let everyMonthAppointList = everyMonthAppointResponse.data.object;

                                // 当前月份的可预约结构信息
                                this.appointmentMonthList = everyMonthAppointList;
                                // 设置当前用户的预约信息
                                this.setUserAppointList(userAppointmentList);
                                // 设置当前用户的预约信息
                                let pkgUpgrade = "";
                                if (userAppointmentList.healthUser != null && userAppointmentList.healthUser.pkgUpgrade) {
                                    pkgUpgrade = userAppointmentList.healthUser.pkgUpgrade;
                                }
                                // 根据选择的日期、设置当前日期的体检机构
                                this.setOrgOptionsByDay(everyMonthAppointList, pkgUpgrade);
                            } else if (everyMonthAppointResponse.status == 200) {
                                // 每个月所有机构的预约信息有值时

                                // 设置当前月份的预约信息
                                let everyMonthAppointList = everyMonthAppointResponse.data.object;

                                // 当前月份的可预约结构信息
                                this.appointmentMonthList = everyMonthAppointList;
                                // 根据选择的日期、设置当前日期的体检机构
                                this.setOrgOptionsByDay(everyMonthAppointList, "");

                                // userAppointmentResponse.status != 200 时   
                                // 401 权限不足时，标识没有登录
                                this.loginStatus = 0; // 未登录
                                this.userid = "";
                            } else if (userAppointmentResponse.status == 200) {
                                // 当前用户的预约信息有值时

                                // 设置当前用户的预约信息
                                let userAppointmentList = userAppointmentResponse.data.object;
                                this.setUserAppointList(userAppointmentList);
                            } else {
                                // 当前月的所有机构的预约信息、用户的预约信息都没有时
                                this.$dialog.toast({
                                        mes: "当前月所有机构的预约信息取得失败，请联系客服",
                                        icon: "error",
                                        timeout: 2000
                                    });
                            }
                        } else {
                            this.$dialog.toast({
                                    mes: "预约周期信息的取得取得失败，请联系客服",
                                    icon: "error",
                                    timeout: 2000
                                });
                        }
                    })).catch(() => {
                        this.$dialog.loading.close();
                        this.$message.warning('请求处理失败')
                    });
                } else {
                    // 用户没有登录时：取得预约周期信息、每个月所有机构的预约信息
                    axios.all([
                        this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/activeCycleList"),
                        this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/monthAppointList?yearMonth=" + yearMonth)
                    ])
                    .then(axios.spread((cycleResponse, everyMonthAppointResponse) => {
                        // 上面两个请求都完成后，才执行这个回调方法
                        this.$dialog.loading.close();

                        if (cycleResponse.status == 200) {
                            let healthCycleList = cycleResponse.data.object;
                            // 预约周期的设定处理
                            this.setActiveCycleList(healthCycleList);
 
                            // 预约周期信息取得时
                            this.initFlg == 2;

                            if (everyMonthAppointResponse.status == 200) {
                                let everyMonthAppointList = everyMonthAppointResponse.data.object;

                                // 当前月份的可预约结构信息
                                this.appointmentMonthList = everyMonthAppointList;
                                // 根据选择的日期、设置当前日期的体检机构
                                this.setOrgOptionsByDay(everyMonthAppointList, "");
                            } else {
                                this.$dialog.toast({
                                        mes: "当前月所有机构的预约信息取得失败，请联系客服",
                                        icon: "error",
                                        timeout: 2000
                                    });
                            }
                        } else {
                            this.$dialog.toast({
                                    mes: "预约周期信息的取得取得失败，请联系客服",
                                    icon: "error",
                                    timeout: 2000
                                });
                        }

                    })).catch(() => {
                        this.$dialog.loading.close();
                        this.$message.warning('请求处理失败')
                    });
                }
            } else {
                // this.initFlg == 2时
                // 月份有变化时
                console.log("changeSelectMonth---222----this.loginStatus==="+this.loginStatus)
                // 根据yearMonth，取得当前月份的每一天的各个机构的可预约人数、已预约人数和剩余人数
                // 根据以上取得检索结果和selectDate，设置选择日期的各个机构的可预约人数、已预约人数和剩余人数
                this.$axios.get(this.CONSTANT.wapiBaseUrl + "healthCheck/monthAppointList?yearMonth=" + yearMonth)
                    .then(response => {
                        if (response.status == 200) {
                            // List<HealthOrgCheckedAppointment> appointmentList
                            let everyMonthAppointList = response.data.object;

                            // 当前月份的可预约结构信息
                            this.appointmentMonthList = everyMonthAppointList;
                            // 根据选择的日期、设置当前日期的体检机构
                            // 用户预约信息取得时
                            if (this.healthUserInfo) {
                                let pkgUpgrade = this.healthUserInfo.pkgUpgrade;
                                if (!pkgUpgrade) {
                                    pkgUpgrade = "";
                                }
                                this.setOrgOptionsByDay(everyMonthAppointList, pkgUpgrade);
                            } else {
                                this.setOrgOptionsByDay(everyMonthAppointList, "");
                            }
                        } else {
                            this.$dialog.loading.close();
                            this.$dialog.toast({
                                    mes: "当前月所有机构的预约信息取得失败，请联系客服",
                                    icon: "error",
                                    timeout: 2000
                                });
                        }
                    })
                    .catch(error => {
                        this.$dialog.loading.close();
                        this.$dialog.toast({
                                mes: "当前月所有机构的预约信息取得异常，请联系客服",
                                icon: "error",
                                timeout: 2000
                            });
                    });
            }
        },
        setSelectDate(selectedDate) {
            /**************选择某一天时的处理****************/
            // calendar组件的的 this.$emit("selectDate", selectedDate) 方法
            this.selectedDate = selectedDate;

            this.$dialog.loading.open("请稍后");
            // 根据以上取得检索结果和selectDate，设置选择日期的各个机构的可预约人数、已预约人数和剩余人数 
            // 根据选择的日期、设置当前日期的体检机构
            // 用户预约信息取得时
            if (this.healthUserInfo) {
                let pkgUpgrade = this.healthUserInfo.pkgUpgrade;
                if (!pkgUpgrade) {
                    pkgUpgrade = "";
                }
                this.setOrgOptionsByDay(this.appointmentMonthList, pkgUpgrade);
            } else {
                this.setOrgOptionsByDay(this.appointmentMonthList, "");
            }
        },
        setActiveCycleList(healthCycleList) {
            /****************预约周期的设定处理*******************/
            // 当前活动的周期还没有设定
            if (healthCycleList.length == 0) {
                this.dateActived = 0;

                // 所有日期都不可用（开始和结束日期都是同一天）
                let today = new Date().getTime();
                today = moment(today).format("YYYY-MM-DD");
                //可选开始日期、结束日期
                this.calendar1.begin = [
                        today.split("-")[0],
                        parseInt(today.split("-")[1]),
                        parseInt(today.split("-")[2])
                    ];
                this.calendar1.end = [
                        today.split("-")[0],
                        parseInt(today.split("-")[1]),
                        parseInt(today.split("-")[2])
                    ];

                // 非活性的日期
                this.calendar1.disabled = [[today.split("-")[0], parseInt(today.split("-")[1]), parseInt(today.split("-")[2])]];
            } else {
                this.dateActived = 1;
                // 只会取得一条
                let healthCycle = healthCycleList[0];

                // 预约周期的开始日期，结束日期
                let startDateStr = healthCycle.startDateStr;
                let endDateStr = healthCycle.endDateStr;
                let startDateYear = startDateStr.split("-")[0];
                let startDateMonth = startDateStr.split("-")[1];
                let startDateDay = startDateStr.split("-")[2];
                let endDateYear = endDateStr.split("-")[0];
                let endDateMonth = endDateStr.split("-")[1];
                let endDateDay = endDateStr.split("-")[2];

                // 当前预约周期的起止日期
                this.cycleStartDate =  startDateStr;
                this.cycleEndDate =  endDateStr;

                //可选开始日期、结束日期
                this.calendar1.begin = [
                        startDateYear,
                        parseInt(startDateMonth),
                        parseInt(startDateDay)
                    ];
                this.calendar1.end = [
                        endDateYear,
                        parseInt(endDateMonth),
                        parseInt(endDateDay)
                    ];

                // 最近三天不可以选择
                let today = healthCycle.serverDate * 1000;
                let today1 = moment(today).format("YYYY-MM-DD");
                this.serverToday = today1; // 2018-07-31
                let today2 = moment(today + 1000 * 60 * 60 * 24 * 1).format("YYYY-MM-DD");
                let today3 = moment(today + 1000 * 60 * 60 * 24 * 2).format("YYYY-MM-DD");

                let today1Year = today1.split("-")[0];
                let today1Month = today1.split("-")[1];
                let today1Day = today1.split("-")[2];
                let today2Year = today2.split("-")[0];
                let today2Month = today2.split("-")[1];
                let today2Day = today2.split("-")[2];
                let today3Year = today3.split("-")[0];
                let today3Month = today3.split("-")[1];
                let today3Day = today3.split("-")[2];

                // 非活性的日期
                this.calendar1.disabled = [
                        [today1Year, parseInt(today1Month), parseInt(today1Day)],
                        [today2Year, parseInt(today2Month), parseInt(today2Day)],
                        [today3Year, parseInt(today3Month), parseInt(today3Day)]
                    ];
            }
        },
        setUserAppointList(userAppointmentInfo) {
            /***************当前用户的预约信息的设定处理*****************/
            // 变量初期化
            this.healthUserAppointmentInfo = [];

            // HealthUserAppointVo
            let healthUser = userAppointmentInfo.healthUser;
            let healthDept = userAppointmentInfo.healthDept;
            let userAppointmentList = userAppointmentInfo.userAppointmentList;
            // 设置用户信息
            // 您的数据数据还未导入，不能进行预约。请联系管理员
            if (healthUser == null) {
                this.appointDisabled = 1;
            } else {
                // 当前用户的信息及所属部门
                this.healthUserInfo = healthUser;
                this.healthUserDept = healthDept;
                // 套餐是否升级
                this.selectedPkgUpgrade = healthUser.pkgUpgrade;
            }

            // 设置预约信息
            this.calendar1.events = {};
            this.periodChecked = 0;
            this.checkedDate = "";
            if (userAppointmentList != null && userAppointmentList.length > 0) {
                // {'2016-7-10':'体检完成', '2017-6-02':'已体检', '2018-6-02':'已预约',}
                let checkInfoStr = "{";
                for (var i = 0; i < userAppointmentList.length; i++) {
                    let userAppointmentInfo = userAppointmentList[i];

                    // 根据条件判断只会有一条
                    this.healthUserAppointmentInfo.push(userAppointmentInfo);

                    // 体检状态 1:未预约 2:已预约 3:已取消 4:已体检 5:体检完成
                    // 实际此处应该使用checkInfo.state，现在只统计一次体检数据，不考虑多次情况，应该healthUser.state同样
                    let stateStr = healthUser.state;
                    if (stateStr == "1") {
                        stateStr = "未预约";
                    } else if (stateStr == "2") {
                        stateStr = "已预约";
                    } else if (stateStr == "3") {
                        stateStr = "已取消";
                    } else if (stateStr == "4") {
                        stateStr = "已体检";
                    } else if (stateStr == "5") {
                        stateStr = "体检完成";
                    } else {
                        // 未预约的数据不存在
                        stateStr = "";
                    }

                    // 预约时间
                    let checkDateStr = userAppointmentInfo.checkDateStr;
                    let arrCheckDate = checkDateStr.split("-");
                    checkDateStr = arrCheckDate[0] + this.dateFormat + parseInt(arrCheckDate[1]) + this.dateFormat + parseInt(arrCheckDate[2]);
                    checkInfoStr = checkInfoStr + '"' + checkDateStr + '":"' + stateStr + '", ';

                    // 判断当前体检周期内是否已有预约(实际应根据healthCycle来判断)
                    let today = this.serverToday;
                    if (arrCheckDate[0] == today.split("-")[0]) {
                        this.periodChecked = 1;
                        this.checkedDate = userAppointmentInfo.checkDateStr;
                    }
                }

                checkInfoStr = checkInfoStr.substr(0, checkInfoStr.length - 2);
                checkInfoStr = checkInfoStr + "}";
                this.calendar1.events = JSON.parse(checkInfoStr);
            }
        },
        changePkgUpgrade() {
            /****************套餐是否升级下拉列表变化时的处理****************/
            // 2019.07 升级套餐只在特定机构做，所以选择升级套餐的体检用户只能选择特定机构体检（排除不可做升级套餐的体检机构）。
            if (this.selectedPkgUpgrade == "1") {
                let orgList = this.healthUserDept.orgList;
                if (this.appointmentMonthList.length > 0) {
                    let appointment = {};
                    // 可以进行套餐升级的体检机构LIST
                    let appointmentMonthTempList = [];
                    for (var i = 0; i < this.appointmentMonthList.length; i++) {
                        appointment = this.appointmentMonthList[i];
                        // 帅选可以进行套餐升级的体检机构
                        for (var j = 0; j < orgList.length; j++) {
                            if (appointment.orgId == orgList[j].orgId) {
                                if (orgList[j].pkgUpgradeFlg) {
                                    appointmentMonthTempList.push(appointment);
                                    break;
                                }
                            }
                        }
                    }

                    // 没有可以选择的体检机构时的处理
                    if (appointmentMonthTempList.length == 0) {
                        this.orgAppointFlg = 3;
                    }

                    // 设置当前日期的体检机构下拉列表
                    this.setOrgOptionsByDay(appointmentMonthTempList, this.selectedPkgUpgrade);
                }

            } else {
                // 设置当前日期的体检机构下拉列表(使用全部的可用体检机构)
                this.setOrgOptionsByDay(this.appointmentMonthList, this.selectedPkgUpgrade);
            }
        },
        setOrgOptionsByDay(everyMonthAppointList, selectedPkgUpgrade) {
            /****************根据选择的日期、设置当前日期的体检机构****************/
            // 取得选择的日期
            // yyyy/mm/dd --> yyyy-mm-dd
            let arrSelectDate = this.selectedDate.split(this.dateFormat);
            let selectedDate = arrSelectDate[0] + "-" + arrSelectDate[1] + "-" + arrSelectDate[2];
            
            // 体检套餐下拉列表的设定
            this.setPkgOptions();
            // 设置选中的项
            // 套餐是否升级: 日期变化时需要将套餐是否升级的设成用户的默认值
            //              餐是否升级下拉列表变化时设成用户选择的
            this.selectedPkgUpgrade = selectedPkgUpgrade;

            // 非升级套餐选择时、重新设置orgOptions的选择项标志
            if (this.selectedPkgUpgrade != "1") {
                this.orgAppointFlg = 1; 
            }

            // 重新设置机构LIST
            this.appointmentDateList = [];

            // 体检机构下拉列表的项目的
            let orgOptionList = [];
            let orgInfo = {};
            orgInfo.orgId = 0;
            orgInfo.orgName = "请选择体检机构";
            orgOptionList.push(orgInfo);

            // 2019.07业务单元的体检人员在选择体检机构时只可选择该特定体检机构。
            // 当前登录用户所在部门可以选择的体检机构
            let orgList = [];
            // 用户信息取得时
            if (this.healthUserDept.orgList) {
                orgList = this.healthUserDept.orgList;
            }
            if (everyMonthAppointList.length > 0) {
                let appointment = {};
                for (var i = 0; i < everyMonthAppointList.length; i++) {
                    appointment = everyMonthAppointList[i];
                    // appointmentDateStr = 2018-06-01
                    if (appointment.appointmentDateStr == selectedDate) {
                        orgInfo = {};
                        // 用户信息未导入时，orgList.length==0， orgOptionList.length == 1，
                        // 即使 this.appointmentDateList.length > 0，用户也无法查看有哪些体检机构
                        for (var j = 0; j < orgList.length; j++) {
                            if (appointment.orgId == orgList[j].orgId) {
                                orgInfo.orgId = appointment.orgId;
                                orgInfo.orgName = orgList[j].orgName;
                                // 是否为升级套餐
                                if (this.selectedPkgUpgrade == "1") {
                                    if (orgList[j].pkgUpgradeFlg) {
                                        orgOptionList.push(orgInfo);
                                    }
                                } else {
                                    orgOptionList.push(orgInfo);
                                }
                                break;
                            }
                        }
                        this.appointmentDateList.push(appointment);
                    }
                }

                // 没有可以选择的体检机构时的处理
                if (orgOptionList.length == 1) {
                    // 是否为升级套餐
                    if (this.selectedPkgUpgrade == "1") {
                        this.orgAppointFlg = 3;
                    } else {
                        this.orgAppointFlg = 2;
                    }
                } else {
                    // 当前月份已有体检机构安排预约
                    this.orgAppointFlg = 1;
                }
            } else {
                 // 当前月份还没有体检机构安排预约
                if (this.orgAppointFlg != 3) {
                    this.orgAppointFlg = 0;
                }
            }

            // 设置下拉列表的选项
            this.orgOptions = [];
            if (orgOptionList.length > 0) {

                // 只有选择升级套餐才可选择305医院
                if (this.selectedPkgUpgrade == "0"){
                    var arr1 = orgOptionList.filter((index) => {
                        return index !== 1;
                    });
                    orgOptionList.slice().reverse().forEach(function (item, index, arr1) {
                        if (item.orgName == '解放军三〇五医院') {
                            orgOptionList.splice(arr1.length - 1 - index, 1);
                        }
                    });
                }

                let a = JSON.stringify(orgOptionList);
                let c = a.replace(/orgId/g, "value").replace(/orgName/g, "text");
                this.orgOptions = JSON.parse(c);
            }

            // 设置选中的项
            // 体检机构
            this.selectedOrg = 0;
            // 体检套餐
            let checkedPkgType = 0;
            // 只有一个选择项时，默认选中那一个
            if (orgOptionList.length == 2) {
                let tempOrgId = orgOptionList[1].orgId;
                this.selectedOrg = tempOrgId;
            }
            // 如果有预约，并且选择的日期是预约日期时,设定已经预约的机构
            if (this.periodChecked == 1) {
                for (let i=0; i<this.healthUserAppointmentInfo.length; i++) {
                    let checkedDate = this.healthUserAppointmentInfo[i].checkDateStr.replace(/-/g, this.dateFormat);
                    if (checkedDate == this.selectedDate) {
                        let checkedOrgId = this.healthUserAppointmentInfo[i].orgId;
                        checkedPkgType = this.healthUserAppointmentInfo[i].pkgType;
                        this.selectedOrg = checkedOrgId;
                    }
                }
            }

            // 机构下拉列表变化时的处理
            this.changeSelectedOrg();
            // 只有一个选择项时，默认选中那一个
            // 如果有选择的话，就用设置已预约的数据库设定的套餐类型
            if (checkedPkgType == null) {
                checkedPkgType = 0;
            }

            this.selectedPkg = checkedPkgType;
        },
        changeSelectedOrg() {
            /*****************机构下拉列表变化时的处理************************/
            // 0:该用户可以预约  1:该用户的数据还未导入  2:剩余名额不足不可以预约
            if (this.appointDisabled != 1) {
                // 重新设置判断标识
                this.appointDisabled = 0;
                this.appointmentOrgInfo = {};
                for (var i = 0; i < this.appointmentDateList.length; i++) {
                    let appointment = this.appointmentDateList[i];
                    if (appointment.orgId == this.selectedOrg) {
                        this.appointmentOrgInfo = appointment;
                        // 预约、或者再次预约时
                        if (this.loginStatus == 1 && (this.healthUserInfo.state == 1 || this.healthUserInfo.state == 3)) {
                            if (this.appointmentOrgInfo.remaindNum == 0) {
                                this.appointDisabled = 2;
                            }
                        }
                    }
                }

                // 体检机构变化后，套餐重新设定
                this.setPkgOptions();
            } else {
                this.$dialog.loading.close();
            }
        },
        setPkgOptions() {
            let userAge = this.healthUserInfo.userAge;
            let orgPkgList = [];
            let pkgByOrg = {};

            let defaultPkgCount = 0;
            let defaultPkgByOrg = {};
            let upgradePkgByOrg = {};

            // 体检机构没有选择时
            if (this.selectedOrg == 0) {
                pkgByOrg.pkgId = 0;
                pkgByOrg.pkgName = "体检机构选择后，再选择体检套餐";
                orgPkgList.push(pkgByOrg);
            } else {
                // 取得选择的体检机构
                let orgList = this.healthUserDept.orgList;
                let selectOrg = {};
                for (var i = 0; i < orgList.length; i++) {
                    selectOrg = orgList[i];
                    if (this.selectedOrg == selectOrg.orgId) {
                        break;
                    }
                }
                let pkgListDB = selectOrg.pkgList;
                if (pkgListDB.length > 0) {
                    pkgByOrg.pkgId = 0;
                    pkgByOrg.pkgName = "请选择体检套餐";
                    pkgByOrg.pkgLineAge = 40;
                    orgPkgList.push(pkgByOrg);

                    for (var i = 0; i < pkgListDB.length; i++) {
                        pkgByOrg = {};
                        pkgByOrg.pkgId = pkgListDB[i].pkgId;
                        pkgByOrg.pkgName = pkgListDB[i].pkgName;
                        pkgByOrg.pkgLineAge = pkgListDB[i].pkgLineAge;
                        orgPkgList.push(pkgByOrg);
                        if (pkgListDB[i].isDefault == "1") {
                            defaultPkgCount++;
                            defaultPkgByOrg = pkgByOrg;
                        } else {
                            upgradePkgByOrg = pkgByOrg;
                        }
                    }
                    if (defaultPkgCount != 1)  {
                        orgPkgList = [];
                        pkgByOrg = {};
                        pkgByOrg.pkgId = 0;
                        pkgByOrg.pkgName = "体检机构的套餐设置不正确，请联系客服";
                        pkgByOrg.pkgLineAge = 40;
                        orgPkgList.push(pkgByOrg);

                        this.$dialog.toast({
                                mes: "体检机构的套餐设置不正确，请联系客服",
                                icon: "error",
                                timeout: 2000
                            });
                    } else {
                        // 用户是升级套餐的话，只能选择有胸部CT检查
                        if (this.selectedPkgUpgrade == "1") {
                            orgPkgList = [];
                            pkgByOrg = {};
                            pkgByOrg.pkgId = upgradePkgByOrg.pkgId;
                            pkgByOrg.pkgName = upgradePkgByOrg.pkgName;
                            pkgByOrg.pkgLineAge = defaultPkgByOrg.pkgLineAge;
                            orgPkgList.push(pkgByOrg);
                        } else{
                            // 40周岁以下不可选择（无胸部CT检查）。
                            if (userAge < defaultPkgByOrg.pkgLineAge) {
                                orgPkgList = [];
                                pkgByOrg = {};
                                pkgByOrg.pkgId = defaultPkgByOrg.pkgId;
                                pkgByOrg.pkgName = defaultPkgByOrg.pkgName;
                                pkgByOrg.pkgLineAge = defaultPkgByOrg.pkgLineAge;
                                orgPkgList.push(pkgByOrg);
                            } else {
                                // 40周岁以上（根据身份证号判断年龄）的体检对象可以进行该选择
                            }
                        }
                    }
                } else {
                    pkgByOrg.pkgId = 0;
                    pkgByOrg.pkgName = "选择的体检机构没有设置套餐";
                    pkgByOrg.pkgLineAge = 40;
                    orgPkgList.push(pkgByOrg);
                }
            }

            // 设置下拉列表的选项
            this.pkgOptions = [];
            if (orgPkgList.length > 0) {
                let a = JSON.stringify(orgPkgList);
                let c = a.replace(/pkgId/g, "value").replace(/pkgName/g, "text");
                this.pkgOptions = JSON.parse(c);
            }

            // 设置选中的项  
            if (this.selectedOrg == 0) {
                this.selectedPkg = 0;
            } else {
                if (defaultPkgCount != 1)  {
                    this.selectedPkg = 0;
                } else {
                    // 用户是升级套餐的话，只能选择有胸部CT检查
                    if (this.selectedPkgUpgrade == "1") {
                        this.selectedPkg = upgradePkgByOrg.pkgId;
                    } else {                        
                        if (userAge < defaultPkgByOrg.pkgLineAge) {
                            this.selectedPkg = defaultPkgByOrg.pkgId;
                        } else {
                            // 40周岁以上（根据身份证号判断年龄）的体检对象可以进行该选择
                            this.selectedPkg = 0;
                        }
                    }
                }
                // 只有一个选择项时，默认选中那一个
                // 如果有选择的话，就用数据库的值
                if (orgPkgList.length == 2) {
                    let tempPkgId = orgPkgList[1].pkgId;
                    this.selectedPkg = tempPkgId;
                }
            }

            this.$dialog.loading.close();
        },
        login() {
            this.$router.push("/fastLogin?page=appointment");
        },
        checkup() {
            if (this.selectedOrg == 0) {
                this.$dialog.toast({
                        mes: "请选择体检机构！",
                        timeout: 1500
                    });

                return false;
            }
            if (this.selectedPkg == 0) {
                this.$dialog.toast({
                        mes: "请选择体检套餐！",
                        timeout: 1500
                    });

                return false;
            }

            // 最多可以修改两次
            if (this.healthUserInfo.modifyNum == 2) {
                this.$dialog.alert({mes:'您之前修改的预约次数已经达到两次，如仍需预约，请联系您所在部门的体检负责人。'});
                return false;
            }

            this.healthUserInfo.pkgType = this.selectedPkg;
            this.healthUserInfo.pkgName = this.pkgOptions.find(item => item.value === this.selectedPkg)['text'];

            this.popShow = true;
            // this.appointment("1");
        },
        reCheckup() {
            if (this.checkedDate != null || this.checkedDate != "") {
                this.$dialog.toast({
                        mes: "请先取消预约后才能重新预约！",
                        timeout: 1500
                    });

                return false;
            }

            if (this.selectedOrg == 0) {
                this.$dialog.toast({
                        mes: "请选择体检机构！",
                        timeout: 1500
                    });

                return false;
            }
            if (this.selectedPkg == 0) {
                this.$dialog.toast({
                        mes: "请选择体检套餐！",
                        timeout: 1500
                    });

                return false;
            }

            // 最多可以修改两次
            if (this.healthUserInfo.modifyNum == 2) {
                this.$dialog.alert({mes:'您之前修改的预约次数已经达到两次，如仍需预约，请联系您所在部门的体检负责人。'});
                return false;
            }

            this.appointment("1", this.selectedDate);
        },
        cancelCheckup() {
            // 选中的日期、以及该日期对应的机构名称
            let checkedDate = this.selectedDate;
            let orgName = '';

            // 当前预约周期内的预约件数的取得
            let checkedCount = 0;
            for (let i=0; i<this.healthUserAppointmentInfo.length; i++) {
                let checkDateStr = this.healthUserAppointmentInfo[i].checkDateStr;
                if (this.cycleStartDate <=  checkDateStr && checkDateStr <= this.cycleEndDate) {
                    checkedDate = this.healthUserAppointmentInfo[0].checkDateStr.replace(/-/g, this.dateFormat);
                    orgName = this.healthUserAppointmentInfo[0].orgName;
                    checkedCount++;
                }
            }
            // 当前周期内预约日期大于一条时，需要提示是否选中预约日期
            if (checkedCount > 1) {
                for (let i=0; i<this.healthUserAppointmentInfo.length; i++) {
                    checkedDate = this.healthUserAppointmentInfo[i].checkDateStr.replace(/-/g, this.dateFormat);
                    if (checkedDate == this.selectedDate) {
                        orgName = this.healthUserAppointmentInfo[i].orgName;;
                    }
                }
            }
            // 当前选中的日期不属于预约日期时
            if (orgName == undefined || orgName == '') {
                this.$dialog.toast({
                        mes: "请选择需要取消预约的日期！",
                        timeout: 1500
                    });

                return false;
            }

            // 最多可以修改两次
            let remaindNum = 2 - this.healthUserInfo.modifyNum;

            this.$dialog.confirm({
                title: "确认",
                mes: "您确定取消【" + checkedDate + "】的【" + orgName + "】机构的体检吗？<br>(最多可以修改2次，还剩" + remaindNum + "次)",
                opts: [
                    {
                        txt: "取消",
                        color: false,
                        callback: () => {
                            // 什么也不处理
                        }
                    },
                    {
                        txt: "确定",
                        color: true,
                        callback: () => {
                         this.appointment("2", checkedDate);
                        }
                    }
                ]
            });
        },
        appointment(appointmentFlg, checkedDate) {
            // 预约、重新预约时
            if (appointmentFlg == "1") {
                this.popShow = false;
            }

            let selectDateTime = new Date(checkedDate).getTime();
            let selectDate = moment(selectDateTime).format("YYYY-MM-DD");
            let healthUserRecord = {
                mobPhone: this.healthUserInfo.mobPhone,
                checkDateStr: selectDate,
                orgId: this.selectedOrg,
                pkgUpgrade: this.selectedPkgUpgrade,
                pkgType: this.selectedPkg
            };

            let msg1 = "预约成功";
            let msg2 = "预约失败：";
            let msg3 = "预约失败，请稍后重试:";
            if (appointmentFlg == "2") {
                msg1 = "取消预约成功";
                msg2 = "取消预约失败：";
                msg3 = "取消预约失败，请稍后重试:";
            }

            this.$dialog.loading.open("请稍后");
            this.$httpAjax.post(this.CONSTANT.wapiBaseUrl + "healthCheck/userAppointment?appointmentFlg=" + appointmentFlg, healthUserRecord)
                .then(response => {
                    this.$dialog.loading.close();
                    if (response.status == 200) {
                        if (response.data.status == 1) {
                            this.$dialog.toast({
                                    mes: msg1,
                                    icon: "success",
                                    timeout: 1200
                                });

                            // 重新取得页面数据
                            let selectYear = selectDate.split("-")[0];
                            let selectMonth = selectDate.split("-")[1];
                            setTimeout(() => {
                                                this.calendar1.value = [];
                                                this.init();
                                                this.$refs.calendar1.setToday(selectYear, selectMonth, "M");
                                            }, 600);
                        } else {
                            // Exception时、response.data.status == -1
                            this.$dialog.alert({ mes: msg2 + response.data.msg });
                        }
                    }
                })
                .catch(error => {
                    this.$dialog.loading.close();
                    this.$dialog.alert({ mes: msg3 + error });
                });
        }
    }
};
</script>
<style scoped>
.appointment {
  width: 100%;
  min-height: 100%;
  overflow: hidden;
  background: #87cefa;
}
/* 日历 */
.appointment_top {
  width: 100%;
  height: 7.3rem;
  min-height: 100%;
  box-sizing: border-box;
  line-height: 0.8rem;
  font-size: 0.3rem;
  color: #a1a1a1;
  padding: 0.2rem 0.24rem;
  /* position: fixed;
  z-index: 9; */
}

.appointment_bottom {
  width: 100%;
  height: auto;
  box-sizing: border-box;
  padding: 0.2rem 0.24rem;
  /* padding-top: 7.5rem; */
}

.appointment_bottom > div {
  display: block;
  width: 100%;
  height: auto;
  margin: 0.2rem 0;
  overflow: hidden;
}

/* 预约按钮 */
.appointment_btn {
  width: 80%;
  text-align: center;
  /* margin-top: 0.2rem; */
  height: 1.2rem;
  text-align: center;
  line-height: 56px;
  font-size: 16px;
  color: #c65600;
  cursor: pointer;
  background: url(../../assets/btn.png) no-repeat center;
  background-size: contain;
}

.popContainer {
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    /* height: calc(100% - constant(safe-area-inset-bottom));
    height: calc(100% - env(safe-area-inset-bottom)); */
    z-index:59;
    background:rgba(0, 0, 0, 0.6);
}
.popBox {
    position:fixed;
    top:15%;
    width:94%;
    z-index:99;
    margin-left:0.2rem;
    background:#ffffff;
}

.popMsg {
  width: 80%;
  margin: 0 auto;
  /* display:none; */
  padding: 2px 0;   /*第一个用于上－下，第二个用于左－右*/
  padding-left: 10px;
  height: auto;
  line-height: 30px;
}
.popMsg ul {
  text-align: justify;
  list-style-type: decimal;
  padding-bottom: 10px;
}
.popTitle {
  text-align: center;
  line-height: 20px;
  height: 30px;
  color: #f60;
  font-weight: bold;
  font-size: 16px;
}
.popMsg li {
  color: #f60;
  line-height: 24px;
  font-size: 14px;
}

@media only screen and (width:375px) and (min-height:690px){
  body{
    height:100vh;
  }
}
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-min-device-pixel-ratio: 3) {
    /* 如果以后出现375*812,非ios机型，可以加上下面语句 */
    div {
        padding: 0 0 12px 0;
    }
    @supports (bottom: constant(safe-area-inset-bottom)) or (bottom: env(safe-area-inset-bottom)) {
      div {
          padding: 0;
          bottom: 0;
          margin-bottom: constant(safe-area-inset-bottom);
          margin-bottom: env(safe-area-inset-bottom);
        }
        .popBox {
            height: 70%;
        }
        .appointment_btn {
            margin-top: 0.5rem;
        }
    }
  }
</style>